<?php
include("/var/www/html/new/d/common/auth.php");
include("/var/www/html/new/d/common/errBack.php");
include("/var/www/html/new/d/common/err_code.php");
include("/var/www/html/new/d/class/ProductInfo.php");
include("/var/www/html/new/d/class/Member.php");
include("/var/www/html/new/d/class/DisOrder.php");
include("/var/www/html/new/d/class/abc/DisOrder_H.php");
include("/var/www/html/new/d/class/abc/Product_H.class.php");
include("/var/www/html/new/d/class/Sale.class.php");
include("/var/www/html/new/d/module/common/Db.class.php");

$dbConf = include '/var/www/html/new/d/module/common/db.conf.php';// 远端服务器配置信息
\PFT\Db::Conf($dbConf['remote_1']);
$_REQUEST['c_pids'] = $c_pids = array_filter($_REQUEST['c_pids']);
$_REQUEST['pid']    = $pid    = key($c_pids);
$_REQUEST['tnum']   = $tnum   = current($c_pids);


// 组合生成座位依据
$seat_data = array();
foreach($_REQUEST['c_pids'] as $key=>$ticket_num){
	$seat_data[$key] = array(
		'ticket_num' => $ticket_num,
		'area_id'    => $_REQUEST['c_area'][$key],
	);
}
unset($_REQUEST['c_pids'][$pid]);

$ac = $GLOBALS['_ac'];
$pw = $GLOBALS['_pw'];
$s  = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));

$res = $s->Create_Conn_REC($_SESSION['account'], $_SESSION['dname']);
$ac1 = $_SESSION['account'];
$pw1 = $res; // 票付通账号跟密码
$s1  = new SoapClient("http://open.12301.cc/openService/MXSE.wsdl",array('encoding' =>'UTF-8','cache_wsdl' => 0));// 票付通接口地址

$pid = $_REQUEST['pid'] + 0;// 产品ID
$aid = $_REQUEST['aid'] + 0;// 供应商ID
$fid = $_SESSION['sid'];

// 基本信息检查
if(p_match($begintime=$_REQUEST['begintime']))
	exit("<script>alert('下单出错：游玩日期格式不正确');javascript:history.go(-1);</script>");
if(p_match($ordername=$_REQUEST['ordername']))
	exit("<script>alert('下单出错：取票姓名含有非法字符');javascript:history.go(-1);</script>");
if(p_match($ordertel=$_REQUEST['ordertel'])) 
	exit("<script>alert('下单出错：取票人含有非法字符');javascript:history.go(-1);</script>");
if(($tnum=$_REQUEST['tnum'] + 0)==0) 
	exit("<script>alert('下单出错：门票数量不能为零');javascript:history.go(-1);</script>");
if(($venue_id=$_REQUEST['venus_id']+0)==0) 
	exit("<script>alert('下单出错：景区未关联演出场馆');javascript:history.go(-1);</script>");
if(($round_id=$_REQUEST['round_id']+0)==0) 
	exit("<script>alert('下单出错：未选择预定场次');javascript:history.go(-1);</script>");
// if($tnum>10) 
	// exit("<script>alert('下单出错：最多只能预定10张');javascript:history.go(-1);</script>");

// 获取产品数据
$str="select p.id as pid,p.apply_limit,p.salerid,p.p_status,p.apply_did,l.id as lid,l.title as ltitle,l.p_type,t.id as tid,t.tprice,t.pay,t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.buy_limit_up,t.status,t.storage_open,t.storage,t.getaddr,f.dhour,f.series_model,f.mdays,f.v_ID_support from uu_products p left join uu_jq_ticket t on p.id=t.pid left join uu_land l on p.contact_id=l.id left join uu_land_f f on p.id=f.pid where p.id=$pid limit 1";
$GLOBALS['le']->query($str);
$p_info = $GLOBALS['le']->fetch_assoc();


// 是否在售
if($p_info['apply_limit']!=1) exit("<script>alert('下单出错：产品未通过审核');javascript:history.go(-1);</script>");

// 是否有购买权限
$auth = authCheck($fid,$aid,$p_info);
if(!$auth['auth']) exit("<script>alert('下单出错：无权限购买');javascript:history.go(-1);</script>");






// 价格获取
$xml = $s->Dynamic_Price_And_Storage($_SESSION['account'], $pid, $begintime, 1, 0, 1, $aid);
if($xml==105 || $xml==1065) exit("<script>alert('下单出错：出游时间无价格');javascript:history.go(-1);</script>");

$obj = simplexml_load_string($xml);
$tprice = (string)$obj->Rec->UUsprice;
$totalMoney = $tprice*$tnum;


$paymodel = abs($_REQUEST['paymode']);
if($paymodel==1) exit("<script>alert('下单出错：不支持在线支付');javascript:history.go(-1);</script>");
if($paymodel==2){
	$fundXml  = $s->PFT_Member_Fund($fid, 1, $aid);
	$fundXml1 = simplexml_load_string($fundXml);
	$fundXml  = $s->PFT_Member_Fund($fid,2,$aid);
	$fundXml2 = simplexml_load_string($fundXml);
	$canUseMoney = (string)$fundXml1->Rec->UUkmoney + (string)$fundXml2->Rec->UUbasecredit;
	if(($canUseMoney)<$totalMoney) exit("<script>alert('下单出错：授信不足');javascript:history.go(-1);</script>");
}

if($paymodel == 0){
	$fundXml = $s->PFT_Member_Fund($fid);
	$fundXml = simplexml_load_string($fundXml);
	if((string)$fundXml->Rec->UUamoney < $totalMoney) exit("<script>alert('下单出错：账户不足');javascript:history.go(-1);</script>");
}
if($paymodel==3) $paymodel=0;// 自销传0不扣钱

$idcard = '';
$idcards = array();
$totalTnum = $tnum;
for($n=1;$n<($totalTnum+1);$n++){
	if($_REQUEST['tourist_name_'.$n] && $_REQUEST['tourist_cert_'.$n]){
		$tourists[]=mysql_real_escape_string($_REQUEST['tourist_name_'.$n]);
		$idcards[]=mysql_real_escape_string($_REQUEST['tourist_cert_'.$n]);
	}
}
if(count($idcards)) $idcard = $idcards[0];
// print_r($_REQUEST);
// echo $idcard;
// exit;

$simxml = $s1->__soapCall("PFT_Order_Submit",array(
		"ac"   => $ac1, //账号
		"pw"   => $pw1, //密码
		"in0"  => $p_info['lid'], //景区id
		"in1"  => $p_info['tid'],//门票id
		"in2"  => '',//远端订单号
		"in3"  => $tprice, //门票价格
		"in4"  => $tnum,//数量
		"in5"  => $begintime,//游玩日期
		"in6"  => $ordername, //客户姓名
		"in7"  => $ordertel,//客户手机号
		"in8"  => '', //联系人手机号
		"in9"  => 0,//是否发送短信（0发送1不发送）
		"in10" => $paymodel,//扣款方式（0使用账户余额2使用供应商处余额4现场支付
		"in11" => 0,//下单方式（0正常下单1手机用户下单）
		"in12" => "",//集合地点
		"in13" => json_encode(array($venue_id, $round_id, $_REQUEST['c_area'][$pid])),//团号
		"in14" => 0,//联票ID
		"in15" => 0,//套票ID
		"in16" => $aid,//供应商id
		"in17" => $idcard//身份证
	)
);

$ph = new abc777\Product_H(\PFT\Db::Connect());
$simxml_o = simplexml_load_string($simxml);
if((string)$simxml_o->Rec->UUerrorcode){
	$url="orderFailure.html?msg=库存不足";
	header("Location:$url");
	exit;
}
$ordernum = (string)$simxml_o->Rec->UUordernum;
// $ph->update_seat_order($ordernum, $_SESSION['sid']);
$url="orderSuc.html?ordernum=$ordernum";
if($_SESSION['dtype']==6){
	$daction="预订订单($r)";
	$str="insert pft_d_operation_rec set fid=".$_SESSION['memberID'].",sid=".$_SESSION['sid'].",rectime=now(),daction='$daction'";
	$GLOBALS['le']->query($str);
}
// 常用联系人存储
$m=new Member($s,$_SESSION['sid']);
if($_REQUEST['saveTo']==1) $m->addCinfo($ordername,$ordertel);
header("Location:$url");


exit;

$pid = $_REQUEST['pid'] + 0;
$aid = $_REQUEST['aid'] + 0;
$m   = new Member($s, $_SESSION['sid']);
$pro = new ProductInfo($s, $pid, $aid);
$disOrder = new DisOrder_H($s, $pro, $m);


if($pid==0) getOut("index.html");







$totalTnum=$tnum;
foreach((array)$_REQUEST['c_pids'] as $c_pid=>$c_num){
	$totalTnum += $c_num;
}


$tourists=array();
$idcards=array();
for($n=1;$n<($totalTnum+1);$n++){
	if($_REQUEST['tourist_name_'.$n] && $_REQUEST['tourist_cert_'.$n]){
		$tourists[]=mysql_real_escape_string($_REQUEST['tourist_name_'.$n]);
		$idcards[]=mysql_real_escape_string($_REQUEST['tourist_cert_'.$n]);
	}
}
if(count($idcards)) $option['sfz'] = $idcards[0];
$option=array();
$option["pid"]         = $pid;
$option["tnum"]        = $tnum;
$option["c_pids"]      = $_REQUEST['c_pids'];
$option["ordertel"]    = $ordertel;
$option["begintime"]   = $begintime;
$option["leavetime"]   = $_REQUEST['leavetime'];
$option["ordername"]   = trim($ordername);
$option["remoteorder"] = $remoteorder;
$option["from"]        = $_REQUEST['from'];
$option['memo']        = mysql_real_escape_string($_REQUEST['memo']);
$option['origin']      = $_REQUEST['origin'];
$option['idcards']     = $idcards;
$option['paymode']     = $paymode;
$option['tourists']    = $tourists;
// $option['c_area']      = $_REQUEST['c_area'];
$option['seat_data']   = $seat_data;
$option['round_id']    = $round_id;;
$option['venue_id']    = $venue_id;;


if(isset($_REQUEST['sfz'])) $option['sfz']=$_REQUEST['sfz'];



function getOut($url,$msg=null){
	$js="<script>";
	if($msg){ $js.="alert('$msg');" ;}
	$js.="window.location='$url'</script>";
	exit($js);
}

function write_logs($txt,$file="/var/www/html/new/d/logs/orderInfo_logs.txt"){
	$fp = fopen($file,"a");
	flock($fp, LOCK_EX);
	fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}

// 购买权限认证 分销商ID 上级供应ID 产品ID
function authCheck($fid,$aid,$p_info){
    $arr = array('self'=>false,'auth'=>false);
    $pid = $p_info['pid'];
    if($p_info['apply_did']==$fid){ // 自供应
        $arr['self'] = true;
        $arr['auth'] = true;
        return $arr;
    }
    if($p_info['apply_did']==$aid){ // 直接供应
        $sql="select pids from `pft_product_sale_list` where fid=$fid and aid=$aid LIMIT 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $pids=$GLOBALS['le']->f("pids");
        if($pids=='A') $arr['auth'] = true;
        if(in_array($pid,explode(",",$pids)))$arr['auth'] = true;
        return $arr;
    }
    // 多手供应
    $sql="select * from pft_p_apply_evolute where pid=$pid and sid=$aid and fid=$fid and status=0 limit 1";
    $GLOBALS['le']->query($sql);
    if($row=$GLOBALS['le']->fetch_assoc())$arr['auth'] = true;
    return $arr;
}
?>